package com.share.PACManager.task;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.share.PACManager.model.CodeModel;
import com.share.PACManager.model.ModifiedModel;
import com.share.PACManager.model.TerminalModel;
import com.share.PACManager.net.HTTPResponse;
import com.share.PACManager.net.HttpUtility;
import com.share.PACManager.utils.Cryptography;
import com.share.PACManager.utils.Utils;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;


public class GetCodeTask extends Thread{

	private GetCodeListener mListener;
	private Context mContext;	
	private TerminalModel mTerminal;
	private ModifiedModel mModified;
	
	public interface GetCodeListener {
		public TerminalModel requestTerminal();
		public ModifiedModel requestModified();
		public void onCheckCode(boolean result, String name, String content);
		public void onCheckResult(boolean result);
	}

	public GetCodeTask(Context context) {
		mContext = context;
	}
	
	public void start(GetCodeListener listener) {
		mListener = listener;
		if(mListener != null)
		{
			mTerminal = mListener.requestTerminal();
			mModified = mListener.requestModified();
			
			start();
		}
	}

	private Handler handler = new Handler(){		
		@Override
		public void handleMessage(Message msg)
		{
			if(mListener != null)
			{
				if(msg.what == 0)
				{
					Bundle data = msg.getData();
					String CodeName = data.getString("CodeName");
					
					HTTPResponse resp = (HTTPResponse) msg.obj;
					List<CodeModel> list = new ArrayList<CodeModel>();
					if(!parse(resp.content, list))
						mListener.onCheckCode(false, CodeName, resp.content);
					else
					{
						mListener.onCheckCode(true, CodeName, resp.content);
						//Utils.saveTmpFile(resp.content, "/sdcard/" + CodeName + ".txt");
					}
				}
				else if(msg.what == 1)
				{
					mListener.onCheckResult(true);
				}
				else
				{
					mListener.onCheckResult(false);
				}
			}
		}
	};
	
    public static boolean parse(String json, List<CodeModel> list)
    {
		try {
			JSONObject jsonObject = new JSONObject(json);
			if(!jsonObject.getBoolean("Success"))
				return false;
			
			JSONArray state = jsonObject.getJSONArray("State"); 
			if(state != null)
			{
				for(int i = 0 ; i < state.length(); i++)
				{
					JSONObject object = state.getJSONObject(i);		
					
					CodeModel code = new CodeModel();		
					
					code.Name = Utils.getJsonString(object, "Name");
					code.Value = Utils.getJsonString(object, "Value");
					code.Code = Utils.getJsonString(object, "Code");
					code.Comment = Utils.getJsonString(object, "Comment");

					list.add(code);
				}				
			}
			
			return true;
			
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return false;
    }
    
	@Override
	public void run() {

		try {

			String modifiedItem = mModified.ModifiedItem;
			//modifiedItem = "Code_Area,Code_CardType,Code_CheckReason,Code_CompanyType,Code_Nation,Code_Native,Code_Sex,Code_TerminalStatus,Code_TerminalType,Code_WorkingStatus";
			//modifiedItem="Code_Sex";
			String[] items = modifiedItem.split(",");
			for(String codeName : items)
			{
				String terminalId = mTerminal.TerminalId;
				String imei = mTerminal.TerminalCode;
				String password = mTerminal.TerminalPassword;
				String ticket = Cryptography.AES_Encode(imei, terminalId, password);
				String info = Cryptography.AES_Encode("CodeName=" + codeName, terminalId, password);
	
				Map<String, String> params = new TreeMap<String, String>();
				params.put("Id", terminalId);
				params.put("TerminalId", terminalId);
				params.put("DataType", "Data");	
				params.put("Password", password);
				params.put("TerminalCode", imei);
				params.put("Version", "1.0");
				params.put("Ticket", ticket);
				params.put("Objective", "GetCode");
				
				String entity = "Information=" + URLEncoder.encode(info);	
				
				Message msg = handler.obtainMessage(0);
				Bundle data = new Bundle();
				data.putString("CodeName", codeName);
				msg.setData(data);
				msg.obj = HttpUtility.httpPost(params, entity);
				msg.sendToTarget();
			}
			handler.obtainMessage(1).sendToTarget();


		} catch (Exception e) {
			handler.obtainMessage(2).sendToTarget();
		}
		
		super.run();
	}
}

	